﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace net.windward.utils
{
    class OfficeVersion
    {
        private const String WORD_SUBKEY = "Word.Application";
        private const String EXCEL_SUBKEY = "Excel.Application";
        private const String POWERPOINT_SUBKEY = "PowerPoint.Application";

        #region check if Office applications are installed

        public static bool isWordInstalled()
        {
            return isAppInstalled(WORD_SUBKEY);
        }

        public static bool isExcelInstalled()
        {
            return isAppInstalled(EXCEL_SUBKEY);
        }

        public static bool isPowerPointInstalled()
        {
            return isAppInstalled(POWERPOINT_SUBKEY);
        }

        private static bool isAppInstalled(string appKey)
        {
            using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(appKey))
            {
                if (key == null)
                    return false;
            }
            return true;
        }

        #endregion

        #region get Office major version

        public static int getOfficeVersion()
        {
            if (isWordInstalled())
            {
                using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(WORD_SUBKEY))
                {
                    return getVersionFromAppKey(key);
                }
            }
            if (isExcelInstalled())
            {
                using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(EXCEL_SUBKEY))
                {
                    return getVersionFromAppKey(key);
                }
            }
            if (isPowerPointInstalled())
            {
                using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(POWERPOINT_SUBKEY))
                {
                    return getVersionFromAppKey(key);
                }
            }

            return -1;
        }

        private static int getVersionFromAppKey(RegistryKey key)
        {
            if (key == null)
                return -1;
            using (RegistryKey curVerSubKey = key.OpenSubKey("CurVer"))
            {
                if (curVerSubKey == null)
                    return -1;
                String version = (String)curVerSubKey.GetValue("");
                int endIndex = version.LastIndexOf('.');
                version = version.Substring(endIndex + 1);
                int versionNum;
                if (int.TryParse(version, out versionNum))
                    return versionNum;
                return -1;
            }
        }

        #endregion
    }
}
